package com.jd.risk.bankorder.service.privilege.authority;

import java.util.List;
import java.util.regex.Pattern;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import com.jd.risk.bankorder.service.privilege.UserService;

/**
 * <p>User: songjunou
 * <p>Date: 2017-05-09
 * <p>Version: 1.0
 */
public class SysUserFilter extends AccessControlFilter {
	
	@Autowired
	private UserService userService;
	
	
	@Value("${unauthorizedurl}")
	private String unauthorizedurl;
	
	@Override
	protected boolean isAccessAllowed(ServletRequest request,
			ServletResponse response, Object mappedValue) throws Exception {
		Subject subject = getSubject(request, response);
		HttpServletRequest  req = (HttpServletRequest)request;
		try {
			if(subject.isAuthenticated() && subject.getPrincipal() != null)
			{
		        String username = (String)SecurityUtils.getSubject().getPrincipal();
		        request.setAttribute("user", userService.findByUsername(username));
				String name = subject.getPrincipal().toString();
				List<String> urls =userService.getUrlByUsername(name);
				String path = req.getServletPath();
				for(String res :urls)
				{
					if(Pattern.matches(res, path))
					{
						return true;
					}
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	@Override
	protected boolean onAccessDenied(ServletRequest request,
			ServletResponse response) throws Exception {
		Subject subject = getSubject(request, response);
		
		try {
			if(!subject.isAuthenticated() || null ==subject.getPrincipal()) //如果没登录或者没有登录信息
			{
					WebUtils.redirectToSavedRequest(request, response, getLoginUrl());
			}else{
					WebUtils.redirectToSavedRequest(request, response, unauthorizedurl);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

   
}
